package com.young.rpc;

import com.google.gson.JsonObject;
import com.young.common.Config;
import com.young.domain.JobExecuteResultEnum;
import com.young.scheduler.grpc.SchedulerModel;
import com.young.scheduler.grpc.VClientSheduleServiceGrpc;
import io.grpc.stub.StreamObserver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @description：
 * @author: yangyahui01
 * @date: 12/3/24 11:39 AM
 */

public class DoJobService extends VClientSheduleServiceGrpc.VClientSheduleServiceImplBase {

    private static final Logger LOGGER = LoggerFactory.getLogger(DoJobService.class);

    @Override
    public void doJob(SchedulerModel.JobRequest request, StreamObserver<SchedulerModel.JobResponse> responseObserver) {

        /**
         * 去执行业务端的方法，这里就不写了
         */

        try {
            // 构建响应体
            JsonObject responseBody = response(JobExecuteResultEnum.SUCCESS);
            SchedulerModel.JobResponse.Builder responseBuilder = SchedulerModel.JobResponse.newBuilder();
            responseBuilder.setMsg(responseBody.toString());
            responseBuilder.setStatus(0);
            // 使用 responseObserver 发送响应
            responseObserver.onNext(responseBuilder.build());
            responseObserver.onCompleted();
        } catch (Exception e) {
            responseObserver.onError(io.grpc.Status.INTERNAL.withDescription("Internal error").asRuntimeException());
            LOGGER.error("Error processing request", e);
        }
    }

    private JsonObject response(JobExecuteResultEnum jobExecuteResultEnum) {
        JsonObject response = new JsonObject();
        response.addProperty("version", Config.VERSION);
        switch (jobExecuteResultEnum) {
            case SUCCESS:
                response.addProperty("status", JobExecuteResultEnum.SUCCESS.getStatus());
                response.addProperty("message", "节点调度成功");
                break;
            case CLIENT_NOT_EXIST:
                response.addProperty("status", JobExecuteResultEnum.CLIENT_NOT_EXIST.getStatus());
                response.addProperty("message", "节点的任务类或方法不存在");
                break;
            case CLIENT_ERROR:
            default:
                response.addProperty("status", JobExecuteResultEnum.CLIENT_ERROR.getStatus());
                response.addProperty("message", "客户端执行任务错误");
                break;
        }
        return response;
    }
}